﻿using FileClient.Core.Client;
using FileClient.Core.Configuration;
using FileEfCore.DbContexts;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;

namespace Microsoft.Extensions.Hosting;

public static class ServiceCollectionExtensions
{
    public static IServiceCollection AddFileClientServices(this IServiceCollection services,
        IConfiguration configuration,string dbName)
    {
        services.AddOptions<FileServerOption>()
            .Bind(configuration.GetSection(FileServerOption.FileServerSetting));
        services.AddSingleton<IBootstrapProvider, DefaultBootstrapProvider>();
        services.AddScoped<IFileServiceClient, DefaultFileServiceClient>();
        services.AddOptions<FileServerOption>()
            .Bind(configuration.GetSection(FileServerOption.FileServerSetting));

        var homeDir = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
        var dbPath = Path.Combine(homeDir, dbName);
        CreateUmsDirectoryIfNotExist(Path.GetDirectoryName(dbPath));
        var connectionString = $"Data Source={dbPath}";
        services.AddDbContext<FileDbContext>(option =>
        {
            option.UseSqlite(connectionString);
            option.UseLoggerFactory(new NullLoggerFactory());
        }, ServiceLifetime.Transient);
        return services;
    }

    private static void CreateUmsDirectoryIfNotExist(string directoryName)
    {
        if (!Directory.Exists(directoryName))
        {
            Directory.CreateDirectory(directoryName);
        }
    }
}